package ru.arriah.servicedesk.web.admin.action;

import java.io.IOException;
import java.util.Collection;
import java.util.regex.Pattern;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ru.arriah.common.web.action.ActionMapping;
import ru.arriah.common.web.action.DumbAction;
import ru.arriah.servicedesk.bean.OrganizationBean;
import ru.arriah.servicedesk.bean.error.OrganizationFormErrorBean;
import ru.arriah.servicedesk.ejb.OrganizationManagerLocalHome;
import ru.arriah.servicedesk.ejb.OrganizationManagerLocalObject;
import ru.arriah.servicedesk.help.Utils;
import ru.arriah.servicedesk.web.commonaction.exception.InternalException;


public class ProcessOrganizationFormAction extends DumbAction {
  protected OrganizationManagerLocalHome organizationManagerHome;  
  protected OrganizationFormErrorBean formErrorBean; 
  
  public ProcessOrganizationFormAction() throws NamingException {
    super();
    
    organizationManagerHome = 
      Utils.getOrganizationManagerHomeInterface();   
  }
  
  
  
  private OrganizationBean restoreBean(HttpServletRequest request) {
     OrganizationBean organizationBean = new OrganizationBean();
     
     organizationBean.setId(idVal(request.getParameter("id")));
     organizationBean.setShortTitle(request.getParameter("shorttitle"));
     organizationBean.setFullTitle(request.getParameter("fulltitle"));
     organizationBean.setPostalAddress(request.getParameter("postaladdress"));
     organizationBean.setKpp(request.getParameter("kpp"));
     organizationBean.setInn(request.getParameter("inn"));
     organizationBean.setSettlementAccount(request.getParameter("settlementaccount"));         
     organizationBean.setBankTitle(request.getParameter("banktitle"));         
     organizationBean.setCorrAccount(request.getParameter("corraccount"));
     organizationBean.setBik(request.getParameter("bik"));
     organizationBean.setTel1(request.getParameter("tel1"));
     organizationBean.setTel2(request.getParameter("tel2"));
     organizationBean.setFax(request.getParameter("fax"));
     organizationBean.setEmail1(request.getParameter("email1"));
     organizationBean.setEmail2(request.getParameter("email2"));
     organizationBean.setWww(request.getParameter("www"));
     organizationBean.setNotes(request.getParameter("notes"));
     organizationBean.setBusinessType(request.getParameter("businesstype"));
     
     return organizationBean;
  }
  
  
  public boolean isValid(OrganizationBean organizationBean) {
    boolean valid = true;
    formErrorBean = new OrganizationFormErrorBean();        
    
    Pattern inn = 
      Pattern.compile(
        config.getProperty("REGEXP.INN"),
        Pattern.CASE_INSENSITIVE
      );
    
    Pattern kpp = 
      Pattern.compile(
        config.getProperty("REGEXP.KPP"),
        Pattern.CASE_INSENSITIVE
      );
    
    Pattern bik = 
      Pattern.compile(
        config.getProperty("REGEXP.BIK"),
        Pattern.CASE_INSENSITIVE
      );
    
    Pattern account = 
      Pattern.compile(
        config.getProperty("REGEXP.ACCOUNT"),
        Pattern.CASE_INSENSITIVE
      );
    
    Pattern email = 
      Pattern.compile(
        config.getProperty("REGEXP.EMAIL"),
        Pattern.CASE_INSENSITIVE
      );
    
    if (organizationBean.getShortTitle().equals("")) {
      formErrorBean.setShortTitle(
        config.getProperty("ERROR.ORGANIZATIONFORM.SHORTTITLE")
      );
      valid = false;
    }
    
    if (organizationBean.getFullTitle().equals("")) {
      formErrorBean.setFullTitle(
        config.getProperty("ERROR.ORGANIZATIONFORM.FULLTITLE")
      );
      valid = false;
    }
                  
    if (organizationBean.getEmail1() == null || organizationBean.getEmail1().equals("")) {
      formErrorBean.setEmail1(
        config.getProperty("ERROR.ORGANIZATIONFORM.EMAIL_INVALID")
      );
      valid = false;
    } else if (!email.matcher(organizationBean.getEmail1()).matches()) {
      formErrorBean.setEmail1(
        config.getProperty("ERROR.ORGANIZATIONFORM.EMAIL_INVALID")
      );
      valid = false;
    }
    
    if (!email.matcher(organizationBean.getEmail2()).matches()) {
      formErrorBean.setEmail2(
        config.getProperty("ERROR.ORGANIZATIONFORM.EMAIL_INVALID")
      );
      valid = false;
    }
    
    if (!inn.matcher(organizationBean.getInn()).matches()) {
      formErrorBean.setInn(
        config.getProperty("ERROR.ORGANIZATIONFORM.INN_INVALID")
      );
      valid = false;
    }
          
    if (!kpp.matcher(organizationBean.getKpp()).matches()) {
      formErrorBean.setKpp(
        config.getProperty("ERROR.ORGANIZATIONFORM.KPP_INVALID")
      );
      valid = false;
    }
    
    if (!bik.matcher(organizationBean.getBik()).matches()) {
      formErrorBean.setBik(
        config.getProperty("ERROR.ORGANIZATIONFORM.BIK_INVALID")
      );
      valid = false;
    }
    
    if (!account.matcher(organizationBean.getCorrAccount()).matches()) {
      formErrorBean.setCorrAccount(
        config.getProperty("ERROR.ORGANIZATIONFORM.CORRACCOUNT_INVALID")
      );
      valid = false;
    } 
    
    if (!account.matcher(organizationBean.getSettlementAccount()).matches()) {
      formErrorBean.setSettlementAccount(
        config.getProperty("ERROR.ORGANIZATIONFORM.SETTLEMENTACCOUNT_INVALID")
      );
      valid = false;
    }      
        
    return valid;    
  }

  
  public String execute(ActionMapping actionMapping,
      HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    try {
      OrganizationBean organizationBean = restoreBean(request);                        
   
      if (!isValid(organizationBean)) {
        addErrorMessage(
           request,
           config.getProperty("ERROR.ORGANIZATIONFORM_FIELDS_INVALID")           
        );
        
        request.setAttribute("organizationBean", organizationBean);
        request.setAttribute("error", formErrorBean);        
        return actionMapping.getFailureTarget();
      }
      
      OrganizationManagerLocalObject organizationManager = 
        organizationManagerHome.create();
                  
      if(organizationBean.getId() == 0) {
        organizationManager.addOrganization(organizationBean);
        
        addInfMessage(
           request,
           config.getProperty("INF.ORGANIZATION_ADDED")
        );
        
      } else {        
        organizationManager.updateOrganization(organizationBean);        
        
        addInfMessage(
           request,
           config.getProperty("INF.ORGANIZATION_UPDATED")
        );
      }
      
      Collection<OrganizationBean> organizationsList = 
        organizationManager.selectOrganizations();
      
      request.setAttribute("organizationsList", organizationsList);      
      organizationManager.remove();
            
      return actionMapping.getSuccessTarget();
    } catch (Exception e) {
      handleException(e, "execute");
      throw new InternalException("ErrorMessage.internal");
    }
  }
}